package com.pengtu.service.test2;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelId;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.stream.ChunkedWriteHandler;

import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

/**
 *@author 刘波波
 *@date 2017年4月7日
 *@describe 用于处理某个bean加载完成前，后执行的某些操作
 */
public class BeanPostPrcessorImpl implements BeanPostProcessor {
	/** 
     * 保存所有WebSocket连接 
     */  
    private Map<ChannelId, Channel> channelMap = new ConcurrentHashMap<ChannelId, Channel>(); 
    private static Map<String,String> ips = new HashMap<String,String>();
	/**
	 *@author 刘波波
	 *@date 2017年4月7日
	 *@describe 
	 */
	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName)
			throws BeansException {
		// TODO Auto-generated method stub
		return bean;
	}

	/**
	 *@author 刘波波
	 *@date 2017年4月7日
	 *@describe simpleServerHandler bean加载完成之后执行定时取实时交通量数据
	 */
	@Override
	public Object postProcessAfterInitialization(final Object bean, String beanName)
			throws BeansException {
			if(beanName.contains("simpleServerHandler")){
			new Thread(new Runnable() {//创建新线程不影响tomcat启动
				public void run() {
				final SimpleServerHandler ssh = (SimpleServerHandler) bean;
//				final AssignTimeHandler ath = new AssignTimeHandler();
//				final TestHandler ath = new TestHandler(BeanPostPrcessorImpl.this);
				EventLoopGroup bossGroup = new NioEventLoopGroup();
				EventLoopGroup workGroup = new NioEventLoopGroup();
				ServerBootstrap b = new ServerBootstrap();
				b.group(bossGroup, workGroup);
				b.channel(NioServerSocketChannel.class); 
				b.childHandler(new ChannelInitializer<SocketChannel>() {
					@Override
					protected void initChannel(SocketChannel ch) throws Exception {
					   ChannelPipeline cp = ch.pipeline();
					   InetSocketAddress sa = (InetSocketAddress) ch.remoteAddress();
						// 保存该Channel的引用  
		               channelMap.put(ch.id(), ch);
//		               ssh.setChannelMap(channelMap);
		               String ip = sa.getAddress().getHostAddress();
		               String port = sa.getPort() +"";
		               System.out.println("new Channel........."+ip +":"+port);
					  // 注册handler    
		               if(ip.contains("119.138.120.28")) {
		            	   cp.addFirst("SimpleServerHandler", ssh);
		               } 
//		               if (ip.contains("192.168.0.55")) 
		               else {
		            	   ips.put(port,ip);
		            	   System.out.println("进来了........................");
		            	   final int MAX_CONTENT_LENGTH = 65536; 
		            	 //编解码http请求  
		       			   cp.addLast("HttpServerCodec",new HttpServerCodec());  
		       			 //保证接收的Http请求的完整性
		                   cp.addLast("HttpObjectAggregator",new HttpObjectAggregator(MAX_CONTENT_LENGTH)); 
		                 //写文件内容  
		                   cp.addLast("ChunkedWriteHandler",new ChunkedWriteHandler());
		                   cp.addLast("TestHandler",new TestHandler(BeanPostPrcessorImpl.this));
//		                   cp.addLast("TestHandler2",new TestDecoderHandler());
		               }
					}
				});
				b.option(ChannelOption.SO_BACKLOG, 128); 
				b.childOption(ChannelOption.SO_KEEPALIVE, true);
				ChannelFuture f = null;
				try {
					f = b.bind(9999).sync();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				// 等待服务器 socket 关闭 。  
				try {
					f.channel().closeFuture().sync();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				}
		}).start();
		}
		return bean;
	}

	public Map<ChannelId, Channel> getChannelMap() {
		return channelMap;
	}

	public void setChannelMap(Map<ChannelId, Channel> channelMap) {
		this.channelMap = channelMap;
	}


	public static Map<String, String> getIps() {
		return ips;
	}

	public static void setIps(Map<String, String> ips) {
		BeanPostPrcessorImpl.ips = ips;
	}

}
